"""
The is doc
"""

import json
import logging
import requests

from django.utils import timezone
from django.views.decorators.http import require_http_methods
from django.http import HttpRequest
from django.core.cache import cache
from django.conf import settings
from django.contrib.auth.base_user import AbstractBaseUser
from django.utils.decorators import method_decorator

from django.views import View

from django.contrib.auth import (
    get_user_model,
    authenticate,
    login,
    logout,
)


from rest_framework.parsers import JSONParser


from app_common import (
    wxapi,
    app_page,
    app_except,
    app_try,
    need_login,
    json_response_utf8_ok,
    try_and_need_login_decorators,
)

from app_community import models as app_community_models

from app_community import ser as app_community_ser

from app_wx_user import models as app_wx_user_models

from app_wx_user import ser as app_wx_user_ser

from . import ser

logger = logging.getLogger("log")


# Create your views here.
dispatch_decorators = [app_try]

check_login_decorators = [need_login]


@method_decorator(dispatch_decorators, name="dispatch")
@method_decorator(check_login_decorators, name="delete")
class AdminLoginView(View):
    def get(self, request, *args, **kwargs):
        if not request.user.is_authenticated:
            raise app_except.NoAccess
        u_s = ser.AppAdminSerializer(request.user)
        return json_response_utf8_ok({"data": u_s.data})

    def post(self, request, *args, **kwargs):
        User = get_user_model()
        _admin = User.objects.filter(id=1).first()
        if not _admin:
            User.objects.create_superuser(
                email="myemail@test.com",
                username="admin",
                password="c0fe91d7d275420d93bffda45990dfdb",
            )

        body: dict = JSONParser().parse(request)

        username = body["username"]
        password = body["password"]
        user = authenticate(request, username=username, password=password)
        if user is not None:
            login(request, user)
        else:
            if request.user.is_authenticated:
                logout(request)
            raise app_except.AdminLoginFail

        u_s = ser.AppAdminSerializer(user)
        return json_response_utf8_ok({"data": u_s.data})

    def delete(self, request, *args, **kwargs):
        user: AbstractBaseUser = request.user
        logout(request)
        return json_response_utf8_ok({"info": f"{user.get_username()} logout"})


@app_try
@require_http_methods(["POST"])
@need_login
def tcb_token(request, _, *args, **kwargs):
    body = JSONParser().parse(request)
    params = {"env": cache.get("ENV_ID"), "path": body["path"]}
    logger.debug(params)
    r = requests.post(wxapi.tcb_token_url, json=params)
    d = json.loads(r.content)
    logger.debug(d)

    return json_response_utf8_ok(d)


@app_try
@require_http_methods(["POST"])
@need_login
def tcb_download(request, _, *args, **kwargs):
    # https://developers.weixin.qq.com/miniprogram/dev/wxcloudrun/src/development/storage/service/download.html
    body = JSONParser().parse(request)
    params = {"env": cache.get("ENV_ID"), "file_list": body["file_list"]}
    logger.debug(params)
    r = requests.post(wxapi.tcb_download_url, json=params)
    d = json.loads(r.content)
    logger.debug(d)

    return json_response_utf8_ok(d)


@method_decorator(try_and_need_login_decorators, name="dispatch")
class AdminWxUserView(View):
    """admin: query user by house"""

    def get(self, request: HttpRequest, *args, **kwargs):
        _objs = app_wx_user_models.WxUser.objects.filter(deleted=False)
        _objs, num_pages = app_page.page(request, _objs)
        m_s = app_wx_user_ser.WxUserSer(_objs, many=True)
        return json_response_utf8_ok({"data": m_s.data, "num_pages": num_pages})


@method_decorator(try_and_need_login_decorators, name="dispatch")
class AdminHouseWxUserView(View):
    """admin: query user by house"""

    def get(self, request: HttpRequest, *args, **kwargs):
        house_uuid = request.GET.get("house_uuid", None)
        user_house_s = app_wx_user_models.WxUserHouse.objects.filter(
            deleted=False
        ).filter(house_uuid=house_uuid)

        user_id_s = [user_house.user_uuid for user_house in user_house_s]
        _objs = app_wx_user_models.WxUser.objects.filter(deleted=False).filter(
            uuid__in=user_id_s
        )
        _objs, num_pages = app_page.page(request, _objs)
        m_s = app_wx_user_ser.WxUserSer(_objs, many=True)
        return json_response_utf8_ok({"data": m_s.data, "num_pages": num_pages})
